<template>
  <div class="page-container search">
    <!-- 搜索头部 -->
    <div class="search-header">
      <van-search
        v-model="searchValue"
        show-action
        placeholder="搜索医院/科室"
        @search="onSearch"
        @input="debouncedSearch"
        @cancel="onCancel"
        autofocus
      >
        <template #action>
          <div @click="onCancel">取消</div>
        </template>
      </van-search>
    </div>

    <!-- 搜索历史 -->
    <div class="search-history" v-if="!searchValue && historyList.length">
      <div class="history-header">
        <span>搜索历史</span>
        <van-icon name="delete" @click="clearHistory" />
      </div>
      <div class="history-tags">
        <span
          v-for="(item, index) in historyList"
          :key="index"
          class="history-tag"
          v-if="historyList[0]!==''"
          @click="onClickHistory(item)"
        >
          {{ item }}
        </span>
      </div>
    </div>

    <!-- 热门搜索 -->
    <div class="hot-search" v-if="!searchValue">
      <div class="hot-header">
        <span>热门搜索</span>
      </div>
      <div class="hot-tags">
        <span
          v-for="(item, index) in hotList"
          :key="index"
          class="hot-tag"
          @click="onClickHot(item)"
        >
          {{ item }}
        </span>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-result" v-if="searchValue">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div v-if="resultList.length === 0 && !loading" class="empty-state">
          <van-empty description="未找到相关医院" />
        </div>
        <div 
          class="result-item" 
          v-for="(item, index) in resultList" 
          :key="index" 
          @click="goToHospital(item)"
        >
          <div class="item-content">
            <h4>{{ item.name }}</h4>
            <p>{{ item.address }}</p>
            <div class="tags">
              <span v-for="(tag, tagIndex) in item.tags" :key="tagIndex" class="tag">
                {{ tag }}
              </span>
            </div>
          </div>
        </div>
      </van-list>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { showConfirmDialog, showToast } from 'vant'
import { userApi, hospitalApi } from '@/api'
import { debounce, processHospitalImage } from '@/utils/utils'

const router = useRouter()
const searchValue = ref('')
const historyList = ref([])
const hotList = ref([])
const resultList = ref([])
const loading = ref(false)
const finished = ref(false)
const currentPage = ref(1)
const pageSize = 10

//获取热门搜索
const getHotData = async () => {
    
    const res = await hospitalApi.getHospitalList()

    if(res.code === 200){
      const firstSixRecords = res.data.records.slice(0, 6);
      hotList.value = firstSixRecords.map(item => item.name);
    }else {
      showToast('获取热门搜索失败')
    }
}

// 搜索医院
const searchHospitals = async (keyword) => {
  try {
    loading.value = true
    const params = {
      name: keyword,
      page: currentPage.value,
      size: pageSize
    }
    
    const res = await hospitalApi.getHospitalList(params)
    if (res.code === 200) {
      // 将搜索结果转换为展示格式
      const newItems = res.data.records.map(item => ({
        ...item,
        tags: [item.grade, item.type]
      }))

      if (currentPage.value === 1) {
        // 第一页，直接替换结果
        resultList.value = newItems
      } else {
        // 其他页，追加结果
        resultList.value = [...resultList.value, ...newItems]
      }

      // 判断是否加载完所有数据
      if (newItems.length < pageSize) {
        finished.value = true
      } else {
        currentPage.value++
      }

      // 更新搜索历史
      updateSearchHistory(keyword)
    }
  } catch (error) {
    console.error('搜索医院失败：', error)
    showToast('搜索失败')
  } finally {
    loading.value = false
  }
}

// 更新搜索历史
const updateSearchHistory = async (keyword) => {
  if (!keyword.trim()) return
  
  // 从本地存储获取用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo'))
  if (!userInfo) return

  // 获取现有搜索历史
  let searchHistory = userInfo.searchHistory ? userInfo.searchHistory.split(',') : []
  
  // 移除重复项
  searchHistory = searchHistory.filter(item => item !== keyword)
  
  // 添加到开头
  searchHistory.unshift(keyword)
  
  // 限制历史记录数量
  if (searchHistory.length > 10) {
    searchHistory = searchHistory.slice(0, 10)
  }
  
  // 将数组转换为逗号分隔的字符串
  const searchHistoryString = searchHistory.join(',')
  
  // 更新本地存储
  userInfo.searchHistory = searchHistoryString
  localStorage.setItem('userInfo', JSON.stringify(userInfo))



  // 通过接口更新数据库搜索历史
  try {
    // await userApi.updateUserInfo({
    //   searchHistory: searchHistoryString // 确保传递字符串类型
    // })
    let params = {
  searchHistory:searchHistoryString,
  id:JSON.parse(localStorage.getItem('userInfo')).id
}
    await userApi.updateUserInfo(params)
    
    // 更新显示的历史记录
    historyList.value = searchHistory
  } catch (error) {
    console.error('更新搜索历史失败：', error)
    showToast('更新搜索历史失败')
  }
}

// 创建防抖的搜索函数
const debouncedSearch = debounce((value) => {
  // 重置搜索状态
  currentPage.value = 1
  finished.value = false
  resultList.value = []
  
  if (value.trim()) {
    searchHospitals(value)
  }
}, 500)

// 监听搜索值变化
watch(searchValue, (newValue) => {
  if (!newValue.trim()) {
    // 当搜索框清空时，重置搜索结果
    resultList.value = []
    currentPage.value = 1
    finished.value = false
  }
})
watch(historyList, (newValue) => {
  console.log('historyList',newValue)
})

// 搜索处理
const onSearch = (value) => {
  if (!value.trim()) return
  currentPage.value = 1
  finished.value = false
  resultList.value = []
  searchHospitals(value)
}

// 取消搜索
const onCancel = () => {
  router.back()
}

// 点击历史记录
const onClickHistory = (value) => {
  searchValue.value = value
  currentPage.value = 1
  finished.value = false
  resultList.value = []
  searchHospitals(value)
}

// 点击热门搜索
const onClickHot = (value) => {
  searchValue.value = value
  currentPage.value = 1
  finished.value = false
  resultList.value = []
  searchHospitals(value)
}

// 清空历史记录
const clearHistory = async () => {
  try {
    await showConfirmDialog({
      title: '提示',
      message: '确定要清空搜索历史吗？'
    })
    
    // 清空本地存储
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    userInfo.searchHistory = ''
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
    
    // 清空后端存储
    await userApi.deleteSearchHistory()
    
    // 清空显示列表
    historyList.value = []
    
    showToast('清空成功')
  } catch (error) {
    console.error('清空搜索历史失败：', error)
    showToast('清空失败')
  }
}

// 跳转到医院详情
const goToHospital = async (hospital) => {
  if(hospital){
    const token = localStorage.getItem('token');
    const processedHospital = await processHospitalImage(hospital, token);
    router.push({
    path: '/hospital',
    query: {
      hospitalData: encodeURIComponent(JSON.stringify(processedHospital))
    }
  })
  }
}

// 加载更多搜索结果
const onLoad = () => {
  if (searchValue.value) {
    searchHospitals(searchValue.value)
  }
}

const getHistoryListData = () =>{
  // 从本地存储中获取 userInfo
const userInfo = localStorage.getItem('userInfo');

// 检查 userInfo 是否存在
if (userInfo) {
    try {
        // 解析 userInfo
        const parsedUserInfo = JSON.parse(userInfo);
        // 检查 parsedUserInfo 中是否有 searchHistory 属性
        if (parsedUserInfo.hasOwnProperty('searchHistory')) {
            // 将 searchHistory 字符串按逗号分割成数组
            const searchHistoryArray = parsedUserInfo.searchHistory?.split(',');
            // 将分割后的数组赋值给 historyList.value
            historyList.value = searchHistoryArray;
        } else {
            console.error('获取搜索历史失败');
            showToast('获取搜索历史失败')
        }
    } catch (error) {
        // 解析 JSON 出错时输出错误信息
        console.error('解析搜索历史时出错:', error);
        showToast('解析搜索历史时出错')
    }
} else {
    // 若本地存储中不存在 userInfo 则输出提示
    console.error('获取搜索历史失败');
    showToast('获取搜索历史失败')
}
}

onMounted( async () => {
  getHistoryListData()
  getHotData()
})
</script>

<style lang="scss" scoped>
.search {
  .search-header {
    position: sticky;
    top: 0;
    z-index: 100;
    background: #fff;
  }

  .search-history,
  .hot-search {
    padding: 16px;
    background: #fff;
    margin-bottom: 12px;

    .history-header,
    .hot-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;
      font-size: 14px;
      color: var(--text-color);
    }

    .history-tags,
    .hot-tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .history-tag,
      .hot-tag {
        padding: 6px 12px;
        font-size: 14px;
        color: var(--text-color);
        background: var(--background-color);
        border-radius: 4px;
      }
    }
  }

  .search-result {
    padding: 16px;

    .result-item {
      margin-bottom: 16px;
      padding: 16px;
      background: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);

      .item-content {
        h4 {
          margin: 0 0 8px;
          font-size: 16px;
          color: var(--text-color);
        }

        p {
          margin: 0 0 8px;
          font-size: 14px;
          color: var(--text-color-secondary);
        }

        .tags {
          display: flex;
          flex-wrap: wrap;
          gap: 8px;

          .tag {
            padding: 2px 8px;
            font-size: 12px;
            color: var(--primary-color);
            background: rgba(11, 181, 132, 0.1);
            border-radius: 4px;
          }
        }
      }
    }
  }
}
</style> 